package com.qf.jie.controller.filter;

import com.alibaba.fastjson.JSON;
import com.qf.jie.entity.vo.RespBean;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/AdminController/*")
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        Object admin = req.getSession().getAttribute("admin");
        // 已登录直接放行
        if (admin != null){
            filterChain.doFilter(req, resp);
            return;
        }
        String servletPath = req.getServletPath();
        String type = req.getParameter("type");
        // 不拦截的请求
        if ("/AdminController".equals(servletPath) && "login".equals(type) ){
            filterChain.doFilter(req, resp);
            return;
        }

        resp.getWriter().write(JSON.toJSONString(RespBean.respError("admin not login")));
    }

    @Override
    public void destroy() {

    }
}
